﻿using Enring.Model.Range;
using System;
using System.Data.Entity;
using System.Linq;

namespace Enring.Web.Install
{
    public partial class Step3 : System.Web.UI.Page
    {
        EnringContext enRing = EnringContext.Current;
        protected void Page_Load(object sender, EventArgs e)
        {
            btnCreate.Click += new EventHandler(btnCreate_Click);
            btnNext.Click += new EventHandler(btnNext_Click);
            enRing.Countries.Load();
            enRing.Languages.Load();
            enRing.Rings.Load();
            enRing.Users.Load();

            lstCountry.DataTextField = "Name";
            lstCountry.DataValueField = "ID";
            lstCountry.DataSource = enRing.Countries.Local.ToBindingList();
            lstCountry.DataBind();

            lstLanguage.DataTextField = "Name";
            lstLanguage.DataValueField = "ID";
            lstLanguage.DataSource = enRing.Languages.Local.ToBindingList();
            lstLanguage.DataBind();

        }

        void btnNext_Click(object sender, EventArgs e)
        {
            Response.Redirect("step4.aspx");
        }

        void btnCreate_Click(object sender, EventArgs e)
        {
            

            string newRingName = txtRing.Text;
            string newUserID = txtUser.Text;
            int cid = int.Parse(lstCountry.SelectedValue);
            int lid = int.Parse(lstLanguage.SelectedValue);
            var hasRing = from r in enRing.Rings where r.Name == newRingName & r.Country.ID == cid select r;
            if (hasRing.Count() <= 0)
            {

                Ring newRing = new Ring()
                {
                    Country = enRing.Countries.Where(c => c.ID == cid).First(),
                    Name = newRingName,
                    Level = 1
                };
                User newUser = new User()
                {
                    Name = newUserID,
                    ParentRing = newRing,
                    DefaultLanguage =
                        enRing.Languages.Where(l => l.ID == lid).First(),
                    CreatedTime = DateTime.Now,
                    LastLoginTime = DateTime.Now,
                    Password = txtPass.Text
                    
                };
                 
               
                
                try
                {
                    enRing.Rings.Add(newRing);
                    enRing.Users.Add(newUser);
                    enRing.SaveChanges();
                    labMess.Text = "创建成功！";
                    btnCreate.Enabled = false;
                    btnNext.Enabled = true;
                }
                catch (Exception err)
                {
                    labMess.Text = "失败:" + err.Message;
                }


            }
            else
                labMess.Text = "公司名称已存在，请更改";
                
            


           

        }
    }
}